package com.foodost.idiomer;

import java.util.List;


import net.youmi.android.AdManager;
import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import net.youmi.android.banner.AdViewListener;
import net.youmi.android.offers.OffersManager;
import net.youmi.android.offers.PointsManager;
import net.youmi.android.spot.SpotManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TaskStackBuilder;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
	
	private static final String TAG = "Idiomer";

    private TextView idiomtvA,idiomtvB,idiomtvC,idiomtvD;
    private TextView counttv,pinyintv,explantv;
    private List<IdiomData> idiomDataList;
    private int index = 0;
    private List<String> idioms;
    private IdiomData idiomData;
    private boolean isShowPinyin = false;
    private int grage;
    private IdiomModel mIdiomModel;
    //umeng share
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	mIdiomModel = new IdiomModel(this);
	initData();
	initView();
	initAds();
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
    	super.onNewIntent(intent);
    	Log.d(TAG, "onNewIntent");
    	int grage = intent.getIntExtra(Constants.GRAGE_INTENT, 1);
    	if(this.grage != grage){
    		initData();
        	index = 0;
        	idiomData = idiomDataList.get(index);
            idioms = getIdioms(idiomData);
        	showPinyin(pinyintv);
        	idiomtvA.setEnabled(true);
        	idiomtvB.setEnabled(true);
        	idiomtvA.setText(idioms.get(0));
        	idiomtvB.setText(idioms.get(1));
        	counttv.setText(String.valueOf(index));
    	}
    	
    }
    
    //从数据库获取数据
    public void initData(){
    	grage = Utils.getOrmGrage(this);
    	idiomDataList = mIdiomModel.getIdiomDatas(this, grage, 0);
    }
    public void initView(){
	idiomtvA = (TextView)findViewById(R.id.idiom_a);
	idiomtvB = (TextView)findViewById(R.id.idiom_b);
	idiomtvC = (TextView)findViewById(R.id.idiom_c);
	idiomtvD = (TextView)findViewById(R.id.idiom_d);
	counttv  = (TextView)findViewById(R.id.count);
	pinyintv = (TextView)findViewById(R.id.pinyin);
	explantv = (TextView)findViewById(R.id.shiyi_title);
	idiomData = idiomDataList.get(index);
    idioms = getIdioms(idiomData);
	showPinyin(pinyintv);
	idiomtvA.setText(idioms.get(0));
	idiomtvB.setText(idioms.get(1));
	idiomtvA.setOnClickListener(this);
	idiomtvB.setOnClickListener(this);
	explantv.setOnClickListener(this);
	pinyintv.setOnClickListener(this);
	
//	resetBackground();
	
	AdView adView = new AdView(this,AdSize.FIT_SCREEN);
	LinearLayout adLayout = (LinearLayout)findViewById(R.id.adLayout);
	adLayout.addView(adView);
	adView.setAdListener(adViewLsn);
    }
    
    
    public void initAds(){
    	SpotManager.getInstance(this).loadSpotAds();
    }
    
    private AdViewListener adViewLsn = new AdViewListener() {
		
		@Override
		public void onSwitchedAd(AdView arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onReceivedAd(AdView arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onFailedToReceivedAd(AdView arg0) {
			// TODO Auto-generated method stub
			
		}
	};
	
	private void showPinyin(TextView tv){
	    if(isShowPinyin){
	        pinyintv.setText(Utils.getPinyin(idiomData.getIdiomRight()));
	    }else{
	        pinyintv.setText(R.string.show_pinyin);
	    }
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	getMenuInflater().inflate(R.menu.main, menu);
	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	Log.d(TAG, "onOptionsItemSelected = " + item.getItemId());
    	/*if(item.getItemId() == R.id.action_share){
    		Log.d(TAG, "R.id.action_share");
    	}else */if(item.getItemId() == R.id.action_reset){//重启此activity
    	    this.recreate();
    	}else if(item.getItemId() == R.id.action_settings){
        	Intent in = new Intent();
        	in.setClass(this, Settings.class);
        	startActivity(in);
        }
    	return super.onOptionsItemSelected(item);
    }
    

    @Override
    protected void onDestroy() {
    	SpotManager.getInstance(this)
        .unregisterSceenReceiver();
    	super.onDestroy();
    }
    @Override
    public void onClick(View v) {
        boolean flag = false; 
        if(v.getId() == R.id.idiom_a){
        	flag = idiomtvA.getText().toString().equals(getIdiom().getIdiomRight());
        	setIdiomViewBackgroundAndCount(v, flag);
        	
        }else if(v.getId() == R.id.idiom_b){
        	flag = idiomtvB.getText().toString().equals(getIdiom().getIdiomRight());
        	setIdiomViewBackgroundAndCount(v, flag);
        }else if(v.getId() == R.id.shiyi_title){
           Intent in = new Intent();
           in.putExtra(Constants.IDIOM_RIGHT, idiomData.getIdiomRight());
           in.setClass(this, ExplanActivity.class);
           startActivity(in);
        }else if(v.getId() == R.id.pinyin){
            isShowPinyin = !isShowPinyin;
            showPinyin(pinyintv);
        }
        
    }
    //根据点击后所在TextView内容与正确成语的比较结果，设置该TextView背景，正确增加计数，错误游戏结束
    public void setIdiomViewBackgroundAndCount(View v,boolean flag){
    	if(flag){
    		v.setBackgroundResource(R.drawable.bg_pressed_right);
    		counttv.setText(String.valueOf(index+1));
    	}else{
    		v.setBackgroundResource(R.drawable.bg_pressed_error);
    		gameOver(R.string.idiom_failed);
    	}
    	if(flag){
            idiomtvA.startAnimation(setIdiomViewAnimation(idiomtvA));
            idiomtvB.startAnimation(setIdiomViewAnimation(idiomtvB)); 
        }
    }
    //成语TextView动画
    public Animation setIdiomViewAnimation(View v){
        final View mV = v;
        float x = v.getPivotX();
        float y = v.getPivotY();
        int width = v.getWidth();
        int height = v.getHeight();
        RotateAnimation rAnim = new RotateAnimation(0, 360,width/2 + x,height/2 + y);
        rAnim.setDuration(500);
        AnimationSet animSet = new AnimationSet(false);
        animSet.addAnimation(rAnim);
        animSet.setAnimationListener(new Animation.AnimationListener() {
            
            @Override
            public void onAnimationStart(Animation animation) {
                
            }
            
            @Override
            public void onAnimationRepeat(Animation animation) {
                
            }
            
            @Override
            public void onAnimationEnd(Animation animation) {
                if(mV.getId() == R.id.idiom_a){
                    resetView();
                }
                
            }
        });
        return animSet;
    }
    //更新成语TextView和拼音内容
    public void resetView(){
        getNextIdiomData();
        if(idiomData != null){
            idioms = getIdioms(idiomData);
            idiomtvA.setText(idioms.get(0));
            idiomtvB.setText(idioms.get(1));
            showPinyin(pinyintv);
            idiomtvA.setBackgroundResource(R.drawable.bgselector);
            idiomtvB.setBackgroundResource(R.drawable.bgselector); 
        }else{
            idiomtvA.setBackgroundResource(R.drawable.bgselector);
            idiomtvB.setBackgroundResource(R.drawable.bgselector);
            gameOver(R.string.idiom_end);
        }
    }
    
    public void gameOver(int strRedId){
        idiomtvA.setEnabled(false);
        idiomtvB.setEnabled(false);
        showOneGrageFinishDialog(R.string.grage_normal_str);
    }
    
    public void showOneGrageFinishDialog(int resId){
	    AlertDialog.Builder builder = new Builder(MainActivity.this);
	    String content = MainActivity.this.getResources().getString(resId, idiomDataList.size(),index);
	    builder.setMessage(content);
	    builder.setTitle(R.string.grage_over);
	    builder.setNegativeButton(R.string.action_reset, new DialogInterface.OnClickListener() {

	     @Override
	     public void onClick(DialogInterface dialog, int which) {
	      dialog.dismiss();
	      MainActivity.this.recreate();
	     }
	    });
	    AlertDialog dialog = builder.create();
	    dialog.setCanceledOnTouchOutside(false);
	    if(!dialog.isShowing()){
	        dialog.show(); 
	    }
	    
	}
    //获取到下一个进入的成语
    public IdiomData getNextIdiomData(){
        if(idiomDataList.size() -1> index){
            idiomData = idiomDataList.get(++index);
        }else{
            idiomData = null;
        }
        return idiomData;
    }

    //得到打乱后的成语列表
	public List<String> getIdioms(IdiomData idiomData) {
		return mIdiomModel.mixIdiom(idiomData);
	}

	public IdiomData getIdiom() {
		return idiomData;
	}
	
    
}
